package com.raychi.demo.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import com.raychi.demo.dao.StudentDao;
import com.raychi.demo.entity.Student;
import com.raychi.demo.util.JdbcUtil;
import com.raychi.demo.util.SessionUtil;

public class StudentService {
	private StudentDao studentDao;
	/**
	 * 登陆验证
	 * @param username 页面输入的用户名
	 * @param password 页面输入的密码
	 * @return 如果输入的用户名和密码能从数据库中查到就登录成功
	 */
	public boolean loing (String username, String password) {
		Connection conn = null;
		Student student = null;
		boolean result = false;
		try{
			conn = JdbcUtil.getConnection();
			student = studentDao.getStudentByUsernameAndPassword(conn, username, password);
			if (student != null) {
				SessionUtil.setStudentSession(student);
				result = true;
			}
		}catch(Exception e){
			JdbcUtil.rollback(conn);
		}finally{
			JdbcUtil.closeConnection(conn);
		}
		return result;
		
	}
	
	public Student getStudentById(int id) throws ClassNotFoundException, SQLException{
		return studentDao.getStudentById(id);
	}
	
	public void delete(int id) throws Exception{
		studentDao.delete(id);
	}
	/**
	 * 用户注册时判断是否该用户名已被注册，如果查到有就注册失败
	 * 没有查到就将用户的注册信息存入数据库
	 */
	
	public String save(Student student){
		Connection conn = null;
		String rsl = "succ";
		
		try{
			conn = JdbcUtil.getConnection();
			int count = studentDao.getCountStudentByUsername(conn, student.getUsername());
			if (count > 0) {
				rsl = "fail";
			} else {
				studentDao.save(student, conn);
				conn.commit();
			}
		}catch(Exception e){
			JdbcUtil.rollback(conn);
		}finally{
			JdbcUtil.closeConnection(conn);
		}
		return rsl;
	}
	
	public void update(Student student) throws Exception{
		studentDao.update(student);
	}
	/**
	 * 获取所有学生的信息列表
	 * @return 所有学生的信息表单
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public List<Student> listStudents() throws ClassNotFoundException, SQLException{
		Connection conn = null;
		List<Student> list = null;
		try{
			conn = JdbcUtil.getConnection();
			list = studentDao.listStudent(conn);
			conn.commit();
		}catch(Exception e){
			JdbcUtil.closeConnection(conn);
		}finally{
			JdbcUtil.rollback(conn);
		}
		return list;
	}
	

	
	public void setStudentDao(StudentDao studentDao) {
		this.studentDao = studentDao;
	}
}
